package com.bwf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Version v1.0
 * @Description: TODO
 * @Author ZHANZHONGXIN
 * @Date 2022/6/14 9:18
 * @Copyright 博为峰
 */
public class LoginFilter implements Filter {
    private List<String> list = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String notFilter = filterConfig.getInitParameter("notFilter");
        String[] strings = notFilter.split(",");
        list = Arrays.asList(strings);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String servletPath = request.getServletPath();
        if (list.contains(servletPath)) {
            filterChain.doFilter(request, response);
        } else {
            HttpSession session = request.getSession();
            String email = (String) session.getAttribute("email");
            if (email != null && email.equals("zhangsan@163.com")) {
                filterChain.doFilter(request, response);
            } else {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        }

    }
}
